/*
 * @Author: anonymous
 * @Date: 2022-01-24 02:38:19
 * @LastEditors: anonymous
 * @LastEditTime: 2022-05-19 17:10:22
 * @Description: 公共函数
 */
import axios from '@/js/axios'
import { ElMessage } from 'element-plus'

/**
 * @description: 保存用户登录信息到localStorage,并清空socketID
 * @param {*} data json对象
 * @return {*}
 * @Author: anonymous
 */
export function saveLoginInfo (data) {
  if (!data) {
    console.error('保存登录信息失败: 数据为空');
    return;
  }

  try {
    // 深拷贝
    let obj = JSON.parse(JSON.stringify(data));
    // 确保loginType有值，默认为user
    const loginType = obj.loginType || 'user';
    
    console.log(`保存${loginType}类型用户登录信息`, obj);
    
    // 清除之前可能存在的其他类型用户的登录信息
    clearLoginInfo();
    
    // 使用登录类型作为前缀来区分不同类型用户的token
    localStorage.setItem(`satoken_${loginType}`, obj.satoken);
    // 存储当前登录类型
    localStorage.setItem("currentLoginType", loginType);
    
    delete obj.satoken;
    localStorage.setItem(`userInfo_${loginType}`, JSON.stringify(obj));
    sessionStorage.removeItem("socketID");
  } catch (error) {
    console.error('保存登录信息失败:', error);
    ElMessage.error('保存登录信息失败');
  }
}

export function getUserInfo () {
  const loginType = localStorage.getItem("currentLoginType") || 'user';
  const userInfoKey = `userInfo_${loginType}`;
  
  const userInfo = localStorage.getItem(userInfoKey);
  if (!userInfo) return null;
  
  try {
    const parsedInfo = JSON.parse(userInfo);
    return {
      nickname: parsedInfo['nickname'] || parsedInfo['username'] || '用户',
      headimgurl: parsedInfo['headimgurl'] || '',
      loginType: parsedInfo['loginType'] || loginType,
      username: parsedInfo['username'] || '',
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
}

/**
 * @description: 清除[userInfo, satoken]
 * @param {*}
 * @return {*}
 * @Author: anonymous
 */
export function clearLoginInfo () {
  // 清除所有可能的用户类型的信息
  const userTypes = ['user', 'worker', 'admin'];
  userTypes.forEach(type => {
    localStorage.removeItem(`userInfo_${type}`);
    localStorage.removeItem(`satoken_${type}`);
  });
  
  localStorage.removeItem("currentLoginType");
  sessionStorage.removeItem("socketID");
}

/**
 * @description: 设置限流sign，并配置限流时间
 * @param {*} sign 标志
 * @param {*} seconds 秒，默认6秒
 * @return {*} void
 * @Author: anonymous
 * 使用 if (getQps('queryWorkerOrder')) return;
            setQps('queryWorkerOrder');
 */
export function setQps (sign, seconds = 6) {
  let cookie = `${sign} = true; max-age = ${seconds}`;
  document.cookie = cookie;
}

/**
 * @description: 获取限流sign是否存在
 * @param {*} sign 标志
 * @return {*} true:存在，false:不存在
 * @Author: anonymous
 */
export function getQps (sign) {
  let cookieArr = document.cookie.split(";")
  for (let index in cookieArr) {
    let key = cookieArr[index].split("=")[0]
    if (key == sign) {
      // 静默限流：不再弹出提示，仅返回 true 阻止本次操作
      return true;
    }
    if (index == cookieArr.length - 1) {
      return false;
    }
  }
}

/**
 * @description: 处理后端返回数组字符串图片地址
 * @param {*} imgUrl
 * @return {*}
 * @Author: anonymous
 */
export function imgUrlAddress (imgUrl) {
  try {
    // 确保imgUrl是一个字符串
    if (typeof imgUrl !== 'string') {
      console.error("imgUrl不是字符串类型:", typeof imgUrl);
      return [];
    }
    
    // 解析JSON字符串
    let arrUrl = JSON.parse(imgUrl);
    
    // 确保解析后是一个数组
    if (!Array.isArray(arrUrl)) {
      console.error("imgUrl解析后不是数组:", arrUrl);
      return [];
    }
    
    // 处理数组中的每个URL
    if (arrUrl != null && arrUrl.length > 0) {
      return arrUrl.map(url => {
        if (typeof url === 'string') {
          // 检查URL是否已经包含baseURL
          if (url.startsWith(axios.defaults.baseURL)) {
            return url;
          }
          return axios.defaults.baseURL + url;
        }
        console.warn("非字符串URL项:", url);
        return '';
      }).filter(url => url); // 过滤掉空字符串
    }
    
    return arrUrl || [];
  } catch (error) {
    console.error("处理图片URL时出错:", error, "原始值:", imgUrl);
    return [];
  }
}

/**
 * @description: 报修Tag状态样式
 * @param {*} statusCode
 * @return {*}
 * @Author: anonymous
 */
export function repairStatusStyle (statusCode) {
  // [待受理，已受理，已完结，已驳回，待完结]
  if (!statusCode || typeof statusCode !== 'number') {
    console.warn('无效的状态码:', statusCode);
    return 'info';
  }
  
  const styles = ['info', '', 'success', 'danger', 'warning'];
  const index = statusCode - 1;
  
  if (index >= 0 && index < styles.length) {
    return styles[index];
  }
  
  console.warn('未知的状态码:', statusCode);
  return 'info';
}

export function createOrderDetailsStep (orderProcessList = null) {
  let array = new Array();
  let list = orderProcessList;
  if (orderProcessList != null && orderProcessList.length == undefined) list = [orderProcessList];

  list.forEach((item, index) => {
    let steps = {
      orderId: item.orderId,
      currentStep: 0,
      step: {
        contactConfirmation: { title: "联系确认", description: "", status: "" },
        applyMaterial: { title: "申报材料", description: "", status: "" },
        chargeOn: { title: "收费开单", description: "", status: "" },
        orderCompleted: { title: "订单完结", description: "", status: "" }
      }
    }

    Object.keys(steps.step).forEach((key, idx) => {
      steps.step[key].status = item[key]
      if (item[key] == 'process') {
        steps.currentStep = idx;
      }
      if (key == 'orderCompleted' && item[key] == 'success') {
        steps.currentStep = 4;
      }
    })
    array.push(steps);
  })
  return array;
}
